<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { getChatDetail } from "@/api/message";
import { chatDetailVO } from "@/api/message/types";

const props = defineProps<{
  visitorId: string;
  serviceName: string;
}>();

const messages = ref<chatDetailVO[]>([]);
const loading = ref(false);
const total = ref(0);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
});
const messageListRef = ref<HTMLElement>();

const loadMessages = async (isFirstLoad = false) => {
  console.log("加载消息——————————————————————");
  loading.value = true;
  try {
    const { data } = await getChatDetail(
      props.visitorId, 
      props.serviceName,
      queryParams.value
    );
    console.log(data);
    if (isFirstLoad) {
      messages.value = (data.list || []).reverse();
      console.log(messages.value);
      await nextTick();
      if (messageListRef.value) {
        messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
      }
    } else {
      messages.value = [...(data.list || []), ...messages.value];
      console.log(messages.value);
    }
    total.value = data.total;
  } catch (error) {
    console.error('Error fetching chat details:', error);
  } finally {
    loading.value = false;
  }
};

const handleScroll = async (e: Event) => {
  
  const element = e.target as HTMLElement;
  if (element.scrollTop <= 50 && !loading.value && messages.value.length < total.value) {
    queryParams.value.pageNum++;
    const oldScrollTop = element.scrollTop;
    const oldScrollHeight = element.scrollHeight;
    
    await loadMessages();
    
    await nextTick();
    const heightDiff = element.scrollHeight - oldScrollHeight;
    element.scrollTop = oldScrollTop + heightDiff;
  }
};

const handleLoadMore = async () => {
  if (!loading.value && messages.value.length < total.value) {
    queryParams.value.pageNum++;
    await loadMessages();
  }
};

onMounted(() => {
  loadMessages(true);
});
</script>

<template>
  <div class="chat-detail">
    <el-card v-loading="loading" class="chat-container">
      <div 
        v-if="messages.length > 0" 
        ref="messageListRef"
        class="message-list" 
        @scroll="handleScroll"
      >
        <div v-if="messages.length < total" class="load-more">
          <el-button link @click="handleLoadMore">加载更多</el-button>
        </div>
        <div v-for="(message, index) in messages" 
             :key="index" 
             :class="['message-item', message.senderType === 0 ? 'visitor' : 'service']">
          <div class="message-content">
            <div class="message-time">{{ message.createTime }}</div>
            <div class="message-text">{{ message.message }}</div>
          </div>
        </div>
      </div>
      <div v-else class="empty-message">
        暂无聊天记录
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.chat-detail {
  height: 100%;
  padding: 20px;
}

.chat-container {
  height: 100%;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 500px;
  overflow-y: auto;
  padding: 20px;
}

/* 添加滚动条样式 */
.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.message-item {
  display: flex;
  margin-bottom: 12px;
}

.message-content {
  max-width: 70%;
  padding: 12px;
  border-radius: 8px;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.message-text {
  word-break: break-all;
}

.visitor {
  justify-content: flex-start;
}

.visitor .message-content {
  background-color: #f4f4f5;
}

.service {
  justify-content: flex-end;
}

.service .message-content {
  background-color: #e6f4ff;
}

.empty-message {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.load-more {
  text-align: center;
  padding: 10px 0;
  color: #409eff;
  cursor: pointer;
}
</style>